package com.jielihaofeng.netty.twowaycommunication;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import lombok.extern.slf4j.Slf4j;

import java.nio.charset.Charset;

/**
 * @author Johnnie Wind
 * @description 双向通信之 EchoServer
 * @date 2021/11/12 09:54
 */
public class EchoServer {
    public static void main(String[] args) {
        new ServerBootstrap()
                .group(new NioEventLoopGroup())
                .channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<NioSocketChannel>() {
                    @Override
                    protected void initChannel(NioSocketChannel ch) throws Exception {
                        ch.pipeline().addLast(new ChannelInboundHandlerAdapter(){
                            @Override
                            public void channelRead(ChannelHandlerContext ctx, Object msg){
                                ByteBuf byteBuf = (ByteBuf) msg;
                                System.out.println(byteBuf.toString(Charset.defaultCharset()));

                                // 推荐通过ctx的alloc创建ByteBuf
                                ByteBuf response = ctx.alloc().buffer();
                                response.writeBytes(byteBuf);
                                ctx.writeAndFlush(response);

                                // 需要释放 byteBuf 吗？
                                // 要的，谁是最后使用者，谁负责释放
                                byteBuf.release();
                                // 需要释放 response 吗？
                                // 要的，谁是最后使用者，谁负责释放
                                response.release();
                            }
                        });
                    }
                })
                .bind(8088);
    }
}
